/*
 *	project-show-view view
 *  -----------------------------------------------------------------------------------------------------------
 */

site.view('project-show-view', {
	
	route: '/project/view/:id',
	projectViewHtml: null,
	elementId: 'project',
	parent: 'desktop-view',
	
	onLoad: function(settings) {
		var that = this,
		request_data = util.extend(settings, {preview: true});
		this.request({
			url: '/project/show',
			type: 'post',
			dataType: 'json',
			data: request_data,
			success: function(data) {
				that.projectViewHtml = that.createElement('div');
				that.projectViewHtml.setAttribute('id', that.elementId);
				that.projectViewHtml.setAttribute('style', 'display: none;');	
				that.projectViewHtml.innerHTML = data.content;
				
				var o = util.extend({view: that.projectViewHtml}, settings);
				that.startAll(o);
				that.trigger('showProject', that.projectViewHtml);
			}
		});
	},
	
	onUnload: function() {
		this.trigger('hideProject');
		this.projectViewHtml = null;
		this.stopAll();
	}

})

.module('project_manager', function(context) {
	
	var container,
		licence,
	
	actCloseProject = function() {
		context.setView('desktop-view');
		return false;
	};

	context.require('fixedProjectHeader').init();

	return {
		
		init: function(settings) {

			container = context.query(settings.view);
			licence = context.query('#licence');
			
			
			context.query('body').append(settings.view);
			container.delegate('a.button_close', 'click', actCloseProject);
	
		},
		
		destroy: function() {
			container.undelegate('a.button_close', 'click', actCloseProject);
		},
		
		events: {
			showProject: function(htmlView) {
				container.show();
			},
			
			hideProject: function() {
				container.hide();
				container.html('');
				container.remove();
			}
		}
	}
	
})

// Comments
// **************************************************************************************************

.module('comment_request', function(context) {

	var util = context.util,
		query = context.query,
		require = context.require,
		notify = require('notify'),

		project_id,
		processing = false;

	return {
		
		init: function(settings) {
			project_id = settings.id;
		},

		events: {
			
			saveComment: function(data, callback) {
				
				if(processing) {
					return;
				}

				processing = true;
				var request_data = util.extend(data, { id: project_id});

				context.request({	
					
					url: '/project/add_comment',
					dataType: 'json',
					type: "post",
					data: request_data,
					
					success: function(data) {
						
						if(data.success === true) {
							callback && callback.call(null, data);
	
							notify.create("create", {
		                        title: data.message,
		                        text: data.description
                    		}); 

						} else {
							
							var err_msg = '';
						
							util.eachRecursive(data.errors, function(key, val) {
								err_msg += err_msg === '' ? val : '<br/>' + val;
							});
							
							notify.create('create','error-template', {
								title: data.message,
								text: err_msg
							});
						}
					},

					error: function(err) {
						console.log('add comment error: ' + err);
						notify.create('create','error-template', {
							title: 'Error',
							text: 'Comment cannot be added. Service unavailable.'
						});
					},

					complete: function() {
						processing = false;
					}
				});
			}
		}
	}
})

.module('comment_container', function(context) {

	var query = context.query,
		comment_box_header;

	return {
	
		init: function(settings) {
			comment_box_header = query('#add_comment_header');
		},

		events: {
			addComment: function(el, parent) {
				if(parent && parent.length > 0) {
					parent.append(el);		
				} else {
					comment_box_header.before(el);	
				}
			}
		}
	}
})

.module('comment_textbox', function(context) {

	var query = context.query,
		request = context.request,
		require = context.require,
		notify = require('notify'),

		btn_comment,
		comment_text,

	onAddCommentHandler = function(e) {
		
		if(comment_text.val().length > 0) {

			var request_data = {
				content: comment_text.val()
			};
				
			context.trigger('saveComment', request_data, onCommentSaved);
			
			} else {

				notify.create('create','error-template', {
					title: 'Cannot add comment.',
					text: 'Element must not be empty.'
				});
		}

		e.preventDefault();
		return false;
	}

	onCommentSaved = function(data) {
		context.trigger('addComment', data.content);
		comment_text.val('');
	};

	return {
		
		init: function(settings) {
			btn_comment = query('.add_comment');
			comment_text = query('.comment_area');

			// Bind DOM events
			btn_comment.bind('click', onAddCommentHandler);
		},

		destroy: function() {
			// Unbind DOM events
			btn_comment.unbind('click', onAddCommentHandler);
		}
	}
})

.module('comment_answer', function(context) {

	var query = context.query,
		request = context.request,
		require = context.require,
		notify = require('notify'),

		act_answer,
		addCommentForm;

	onAddCommentHandler = function(e) {

		var parent_id = e.data.parent_id,
			comment_text = e.data.comment_text,
			comment_box = e.data.comment_box;

		if(comment_text.val().length > 0) {

			var request_data = {
				content: comment_text.val(),
				parent_id: parent_id
			};
				
			context.trigger('saveComment', request_data, function(data) {
				context.trigger('addComment', data.content, comment_box);
				comment_text.val('');
			});
			
			} else {

				notify.create('create','error-template', {
					title: 'Cannot add comment.',
					text: 'Element must not be empty.'
				});
		}

		e.preventDefault();
		return false;
	}

	function onCommentAnswer(e) {
		
		var comment_box = $(this).parents('article'),
			el = $(this);

		if(comment_box.data('commented') === true) {
			e.preventDefault();
			return false;
		}

		comment_box.data('commented', true);

		var answerCommentForm = addCommentForm.clone();
		answerCommentForm.css({'margin-left': '57px'}).insertAfter(comment_box);

		answerCommentForm.find('.add_comment')					// get from rel
		.bind('click', {
			parent_id: el.attr('rel'), 
			comment_text: answerCommentForm.find('.comment_area'), 
			comment_box: comment_box},
		onAddCommentHandler);

		e.preventDefault();
		return false;
	}

	return {
		
		init: function(settings) {
			act_answer = query('.act_answer');
			addCommentForm = query('.add_comment_form');

			// Bind DOM events
			act_answer.bind('click', onCommentAnswer);
		},

		destroy: function() {
			// Unbind DOM events
			act_answer.unbind('click', onCommentAnswer);
		}
	}	

})

// Appreciate
// **************************************************************************************************

.module('appreciate', function(context) {

	var query = context.query,
		request = context.request,
		tipsy = context.require('tipsy'),
		btn_appreciate,
		appreciate_info,


	onAppreciateHandler = function(e) {
		context.trigger('addAppreciate', onAppreciateSaved);
		e.preventDefault();
		return false;
	},

	onAppreciateSaved = function(data) {
		btn_appreciate.removeClass('button_header')
					  .addClass('button_header_active');

		//TODO: message translation
		btn_appreciate.find('span.appreciate_amount').html('you appreciate it');
	};

	return {
		init: function(settings) {
			tipsy.init('#btn_appreciate', { gravity: 'e'});
			btn_appreciate = query('#btn_appreciate');
			btn_appreciate.bind('click', onAppreciateHandler);
		},

		destroy: function() {
			btn_appreciate.unbind('click', onAppreciateHandler);
		}
	}

})

.module('appreciate_request', function(context) {

	var util = context.util,
		query = context.query,
		require = context.require,
		notify = require('notify'),

		project_id,
		processing = false;

	return {
		
		init: function(settings) {
			project_id = settings.id;
		},

		events: {
			
			addAppreciate: function(callback) {
				
				if(processing) {
					return;
				}

				processing = true;
				var request_data = { id: project_id};

				context.request({	
					
					url: '/project/appreciate',
					dataType: 'json',
					type: 'post',
					data: request_data,
					
					success: function(data) {
						
						if(data.success === true) {
							callback && callback.call(null, data);

						} else {
							
							var err_msg = '';
								
							util.eachRecursive(data.errors, function(key, val) {
								err_msg += err_msg === '' ? val : '<br/>' + val;
							});
							
							notify.create('create','error-template', {
								title: data.message,
								text: err_msg
							});
						}
					},

					error: function(err) {
						console.log('add comment error: ' + err);

						notify.create('create','error-template', {
							title: 'Error',
							text: 'Appreciate cannot be added. Service unavailable.'
						});
					},

					complete: function() {
						processing = false;
					}
				});
			}
		}
	}
})

// Filters
// **************************************************************************************************

.module('filters', function(context) {

	var query = context.query,
		request = context.request,
		has = 'hasOwnProperty',
		btn_filters,
		content,
		filtered_containers = {},

		toggleFilter = function() {
			var el = $(this),
			filter_container_name = '.' + el.data('type') + '_container';

			if(!filtered_containers[has](filter_container_name))
				filtered_containers[filter_container_name] = content.find(filter_container_name);

			el.toggleClass('active');
			filtered_containers[filter_container_name].toggle();
		};

	return {
		init: function(settings) {
			btn_filters = query('#filters li');
			content = query('#content')
			btn_filters.bind('click', toggleFilter);
		},

		destroy: function() {
			btn_filters.unbind('click', toggleFilter);
		}
	}

});